import { Module } from 'vuex'

import { typeLoginState } from './type'
import { typeRootState } from '../type'
import { IAccount } from '@/service/login/type'

import LocalCache from '@/untils/cache'
import {
  accountLoginRequest,
  userInfoRequest,
  userMenuRequest
} from '@/service/login/login'
import router from '@/router'
import { mapMenusToPermissions, mapMenuToRoutes } from '@/untils/map-menus'

const loginModule: Module<typeLoginState, typeRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenu: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenu(state, userMenu: any) {
      state.userMenu = userMenu
      const routes = mapMenuToRoutes(userMenu)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      // 获取用户按钮的权限
      const permissions = mapMenusToPermissions(userMenu)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      // 登录处理
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      LocalCache.setCache('token', token)

      // 请求用户信息
      const userInfoResult = await userInfoRequest(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      LocalCache.setCache('userInfo', userInfo)

      // 请求用户菜单
      const userMenusResult = await userMenuRequest(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenu', userMenus)
      LocalCache.setCache('userMenus', userMenus)

      router.push('/main')
    },
    loadLocalLogin({ commit }) {
      const token = LocalCache.getCache('token')
      if (token) commit('changeToken', token)
      const userInfo = LocalCache.getCache('userInfo')
      if (userInfo) commit('changeUserInfo', userInfo)
      const userMenus = LocalCache.getCache('userMenus')
      if (userMenus) commit('changeUserMenu', userMenus)
    }
  }
}

export default loginModule
